from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QTextEdit, QCheckBox, 
                             QPushButton, QHBoxLayout, QFileDialog)
from PyQt5.QtCore import Qt

def create_log_panel(main_window):
    """创建日志面板"""
    log_panel = QWidget()
    log_layout = QVBoxLayout(log_panel)
    log_layout.setContentsMargins(10, 10, 10, 10)
    
    # 创建日志文本框
    main_window.log_text = QTextEdit()
    main_window.log_text.setReadOnly(True)
    main_window.log_text.setLineWrapMode(QTextEdit.NoWrap)
    
    # 创建控制按钮
    controls_layout = QHBoxLayout()
    
    # 自动滚动选项
    main_window.auto_scroll_check = QCheckBox("自动滚动")
    main_window.auto_scroll_check.setChecked(True)
    
    # 清除按钮
    clear_btn = QPushButton("清除日志")
    clear_btn.clicked.connect(main_window.log_text.clear)
    
    # 保存按钮
    save_btn = QPushButton("保存日志")
    save_btn.clicked.connect(lambda: save_log(main_window))
    
    controls_layout.addWidget(main_window.auto_scroll_check)
    controls_layout.addStretch()
    controls_layout.addWidget(clear_btn)
    controls_layout.addWidget(save_btn)
    
    # 添加到日志布局
    log_layout.addWidget(main_window.log_text)
    log_layout.addLayout(controls_layout)
    
    return log_panel

def save_log(main_window):
    """保存日志到文件"""
    file_dialog = QFileDialog(main_window)
    file_dialog.setWindowTitle("保存日志")
    file_dialog.setNameFilter("文本文件 (*.txt)")
    file_dialog.setAcceptMode(QFileDialog.AcceptSave)
    file_dialog.setDefaultSuffix("txt")
    
    if file_dialog.exec_():
        selected_files = file_dialog.selectedFiles()
        if selected_files:
            log_path = selected_files[0]
            try:
                with open(log_path, 'w', encoding='utf-8') as f:
                    f.write(main_window.log_text.toPlainText())
                main_window.append_log(f"日志已保存到: {log_path}")
            except Exception as e:
                main_window.append_log(f"保存日志失败: {str(e)}")